package com.aw.baselib.widgets

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.View.OnFocusChangeListener
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import com.aw.baselib.R
import com.aw.baselib.util.AwDisplayUtil
import com.aw.baselib.util.AwLog

/**
 * Created by hzw
 * 自定义搜索框
 * 使用方法：
 * 需要设置SearchEditText不自动获取焦点
 * 设置方法：在父控件中加入以下两个属性
 * android:focusable="true"
 * android:focusableInTouchMode="true"
 */
@SuppressLint("AppCompatCustomView")
class SearchEditText(private var mContext: Context, attrs: AttributeSet?, defStyleAttr: Int) :
    EditText(
        mContext, attrs, defStyleAttr
    ), OnFocusChangeListener, View.OnKeyListener, TextWatcher {
    //图标是否默认在左边
    private var isIconLeft = false

    //是否点击软键盘搜索
    private var pressSearch = false

    //软键盘搜索键监听
    private var listener: OnSearchClickListener? = null

    // 控件的图片资源
    private var drawables: Array<Drawable>? = null

    // 搜索图标和删除按钮图标
    private var drawableLeft: Drawable? = null
    private var drawableDel: Drawable? = null

    // 记录点击坐标
    private var eventX = 0
    private var eventY = 0

    // 控件区域
    private var rect: Rect? = null

    /**
     * 构造器
     *
     * @param context
     */
    constructor(context: Context) : this(context, null) {
        mContext = context
        init()
    }

    /**
     * 构造器
     *
     * @param context
     */
    constructor(context: Context, attrs: AttributeSet?) : this(
        context,
        attrs,
        android.R.attr.editTextStyle
    ) {
        mContext = context
        init()
    }

    /**
     * 构造器
     *
     * @param context
     */
    init {
        init()
    }

    /**
     * 初始化函数
     */
    private fun init() {
        onFocusChangeListener = this
        setOnKeyListener(this)
        addTextChangedListener(this)
    }

    /**
     * 绘制
     *
     * @param canvas
     */
    override fun onDraw(canvas: Canvas) {
        if (isIconLeft) { // 如果是默认样式，直接绘制
            if (length() < 1) {
                drawableDel = null
            }
            //drawable的宽高是按drawable固定的宽高,即通过getIntrinsicWidth()与getIntrinsicHeight()获得
            //this.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, drawableDel, null);
            //drawable的宽高是按drawable.setBound()设置的宽高
            setCompoundDrawables(drawableLeft, null, drawableDel, null)
            super.onDraw(canvas)
        } else { // 如果不是默认样式，需要将图标绘制在中间
            if (drawables == null) {
                drawables = compoundDrawables
            }
            if (drawableLeft == null) {
                drawableLeft = drawables!![0]
            }
            val textWidth = paint.measureText(hint.toString())
            val drawablePadding = compoundDrawablePadding
            //int drawableWidth = drawableLeft.getBounds().width();
            val drawableWidth = drawableLeft!!.intrinsicWidth
            val bodyWidth = textWidth + drawableWidth + drawablePadding
            canvas.translate((width - bodyWidth - paddingLeft - paddingRight) / 2, 0f)
            super.onDraw(canvas)
        }
    }

    /**
     * 焦点监听
     *
     * @param v
     * @param hasFocus
     */
    override fun onFocusChange(v: View, hasFocus: Boolean) {
        // 被点击时，恢复默认样式
        if (!pressSearch && TextUtils.isEmpty(text.toString())) {
            isIconLeft = hasFocus
        }
    }

    /**
     * 按键监听
     *
     * @param v
     * @param keyCode
     * @param event
     * @return
     */
    override fun onKey(v: View, keyCode: Int, event: KeyEvent): Boolean {
        pressSearch = keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN
        if (pressSearch && listener != null) {
            /*隐藏软键盘*/
            val imm = v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (imm.isActive) {
                imm.hideSoftInputFromWindow(v.applicationWindowToken, 0)
            }
            listener!!.onSearchClick(v)
        }
        return false
    }

    /**
     * 触摸监听
     *
     * @param event
     * @return
     */
    override fun onTouchEvent(event: MotionEvent): Boolean {
        // 清空edit内容
        if (drawableDel != null && event.action == MotionEvent.ACTION_UP) {
            eventX = event.rawX.toInt()
            eventY = event.rawY.toInt()
            AwLog.d(TAG, "eventX = $eventX; eventY = $eventY")
            if (rect == null) {
                rect = Rect()
            }
            getGlobalVisibleRect(rect)
            rect!!.left = rect!!.right - drawableDel!!.intrinsicWidth
            if (rect!!.contains(eventX, eventY)) {
                setText("")
                if (listener != null) {
                    listener!!.onClearSearch()
                }
            }
        }
        // 删除按钮被按下时改变图标样式
        if (drawableDel != null && event.action == MotionEvent.ACTION_DOWN) {
            eventX = event.rawX.toInt()
            eventY = event.rawY.toInt()
            AwLog.d(TAG, "eventX = $eventX; eventY = $eventY")
            if (rect == null) {
                rect = Rect()
            }
            getGlobalVisibleRect(rect)
            rect!!.left = rect!!.right - drawableDel!!.intrinsicWidth
            if (rect!!.contains(eventX, eventY)) {
                drawableDel = this.resources.getDrawable(R.mipmap.icon_clear_input)
            }
        } else {
            drawableDel = this.resources.getDrawable(R.mipmap.icon_clear_input)
        }
        return super.onTouchEvent(event)
    }

    /**
     * 输入变化监听
     *
     * @param arg0
     */
    override fun afterTextChanged(arg0: Editable) {
        drawableDel = if (length() < 1) {
            null
        } else {
            this.resources.getDrawable(R.mipmap.icon_clear_input)
        }
    }

    override fun beforeTextChanged(arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int) {}
    override fun onTextChanged(arg0: CharSequence, arg1: Int, arg2: Int, arg3: Int) {}

    /**
     * 测量
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (drawables == null) {
            drawables = compoundDrawables
        }
        if (drawableLeft == null) {
            drawableLeft = drawables!![0]
            //drawableLeft.setBounds(0, 0, DensityUtil.dip2px(mContext, 16), DensityUtil.dip2px(mContext, 16));
        }
        if (drawableDel != null) {
            drawableDel!!.setBounds(
                0,
                0,
                AwDisplayUtil.dip2px(mContext, 18f),
                AwDisplayUtil.dip2px(mContext, 18f)
            )
        }
    }

    /**
     * 设置接口
     *
     * @param listener
     */
    fun setOnSearchClickListener(listener: OnSearchClickListener?) {
        this.listener = listener
    }

    /**
     * 定义接口
     */
    interface OnSearchClickListener {
        fun onSearchClick(view: View?)
        fun onClearSearch()
    }

    companion object {
        private val TAG = SearchEditText::class.java.simpleName
    }
}